package com.example.springcloud.service;

import ch.qos.logback.classic.filter.ThresholdFilter;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author weiHuang.zhu
 * @Date 20/4/2023 下午9:48
 */
@Service
@DefaultProperties(defaultFallback = "paymentGlobalFallBackMethod")
public class PaymentService {

    public String paymentInfo(Integer id) {
        return Thread.currentThread().getName() + ",id = "+ id;
    }
    @HystrixCommand
    //    @HystrixCommand(fallbackMethod = "paymentTimeoutHandler",
//            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})
    public String paymentInfo_TimeOut(Integer id) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + ",timeout method ,id=" + id;
    }

    public String paymentTimeoutHandler(@PathVariable("id") Integer id) {
        return Thread.currentThread().getName() + "服务器繁忙！";
    }

    public String paymentGlobalFallBackMethod(@PathVariable("id") Integer id) {
        return Thread.currentThread().getName() + "服务器繁忙！";
    }
    //服务熔断==
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback",
    commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")//失败率达到多少后跳匝
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id<0) {
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber = UUID.randomUUID().toString();
        return Thread.currentThread().getName() + "version: " + serialNumber;
    }

    public String paymentCircuitBreakerFallback(@PathVariable("id")Integer id) {
        return "id不能为负数"+ id;
    }
}
